<template>
  <el-card>
    <h4 class="mb-20px">{{ id === -1 ? '新增' : '编辑' }}</h4>
    <el-row>
      <el-col :span="12">
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="auto"
          v-loading="formLoading"
        >
          <el-form-item label="会议ID" prop="id">
            <el-input v-model="formData.id" placeholder="创建后自动生成" disabled />
          </el-form-item>
          <el-form-item label="会议名称" prop="meetingName">
            <el-input v-model="formData.meetingName" placeholder="请输入会议名称" />
          </el-form-item>
          <el-form-item label="会议简介" prop="meetingSynopsis">
            <el-input
              type="textarea"
              :rows="4"
              resize="none"
              v-model="formData.meetingSynopsis"
              placeholder="请输入会议简介"
            />
          </el-form-item>
          <el-form-item label="会议开始时间" prop="startTime">
            <el-date-picker
              v-model="formData.startTime"
              type="datetime"
              value-format="x"
              placeholder="选择会议开始时间"
            />
          </el-form-item>
          <el-form-item label="会议结束时间" prop="endTime">
            <el-date-picker
              v-model="formData.endTime"
              type="datetime"
              value-format="x"
              placeholder="选择会议结束时间"
            />
          </el-form-item>
          <el-form-item label="是否为免费会议" prop="isFreeMeeting">
            <el-radio-group v-model="formData.isFreeMeeting">
              <el-radio :label="0">是</el-radio>
              <el-radio :label="1">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="formData.isFreeMeeting === 1" label="会议方案" prop="meetingPlanId">
            <el-select v-model="formData.meetingPlanId" placeholder="请选择会议方案" multiple>
              <el-option
                v-for="i in meetingPlanOptions"
                :key="i.id"
                :label="i.schemeName"
                :value="i.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="会议地址" prop="meetingAddress">
            <el-input v-model="formData.meetingAddress" placeholder="请输入会议地址" />
          </el-form-item>
          <el-form-item label="封面" prop="cover">
            <div class="flex items-end">
              <UploadImg v-model="formData.cover" width="100px" height="100px" />
              <span class="ml-10px">1080px*1920px</span>
            </div>
          </el-form-item>
          <el-form-item label="轮播图" prop="carouselImage">
            <div class="flex items-end">
              <UploadImgs v-model="formData.carouselImage" width="100px" height="100px" />
              <span class="ml-10px">1080px*1920px</span>
            </div>
          </el-form-item>
          <el-form-item label="会议详情" prop="details">
            <Editor v-model="formData.details" placeholder="请输入会议详情" />
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input v-model="formData.sort" placeholder="请输入排序" />
          </el-form-item>
          <el-form-item label="是否置顶" prop="isTop">
            <el-switch v-model="formData.isTop" :active-value="1" :inactive-value="0" />
          </el-form-item>
          <el-form-item label="创建时间" prop="createTime">
            <el-input
              :modelValue="formData.createTime && formatDate(formData.createTime)"
              placeholder="创建后自动生成"
              disabled
            />
          </el-form-item>
        </el-form>
        <div>
          <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
          <el-button
            @click="
              () => {
                $router.back()
                delVisitedView(route)
              }
            "
            >取 消</el-button
          >
        </div>
      </el-col>
    </el-row>
  </el-card>
</template>
<script setup lang="ts">
import { SpecialMeetingApi, SpecialMeeting } from '@/api/biz/specialmeeting'
import { MeetingPlanApi, MeetingPlan } from '@/api/biz/meetingplan'
import { formatDate } from '@/utils/formatTime'
import { useTagsViewStore } from '@/store/modules/tagsView'

const { delVisitedView } = useTagsViewStore()
const route = useRoute()
const router = useRouter()

/** 专场会议管理 表单 */
defineOptions({ name: 'SpecialMeetingForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const id = +useRoute().params.id

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  meetingName: undefined,
  meetingSynopsis: undefined,
  startTime: undefined,
  endTime: undefined,
  isFreeMeeting: 0,
  meetingPlanId: [],
  meetingAddress: undefined,
  cover: undefined,
  carouselImage: [],
  details: undefined,
  sort: undefined,
  isTop: 0,
  createTime: undefined
})
const formRules = reactive({
  meetingName: [{ required: true, message: '会议名称不能为空', trigger: 'blur' }],
  meetingSynopsis: [{ required: true, message: '会议简介不能为空', trigger: 'blur' }],
  startTime: [{ required: true, message: '会议开始时间不能为空', trigger: 'blur' }],
  endTime: [{ required: true, message: '会议结束时间不能为空', trigger: 'blur' }],
  isFree: [{ required: true, message: '是否为免费会议（0是 1否）不能为空', trigger: 'blur' }],
  meetingAddress: [{ required: true, message: '会议地址不能为空', trigger: 'blur' }],
  cover: [{ required: true, message: '封面不能为空', trigger: 'blur' }],
  carouselImage: [{ required: true, message: '轮播图不能为空', trigger: 'blur' }],
  details: [{ required: true, message: '会议详情不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const meetingPlanOptions = ref<MeetingPlan[]>([]) // 会议方案下拉选项

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await SpecialMeetingApi.getSpecialMeeting(id)
      data.carouselImage = data.carouselImage?.split(',') || []
      data.meetingPlanId = data.meetingPlanId?.split(',')?.map(Number) || []
      formData.value = data
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const getMeetingPlanOptions = async () => {
  const data = await MeetingPlanApi.getMeetingPlanPage({ pageNo: 1, pageSize: 100 })
  meetingPlanOptions.value = data.list
}
getMeetingPlanOptions()

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as SpecialMeeting
    if (formType.value === 'create') {
      await SpecialMeetingApi.createSpecialMeeting({
        ...data,
        carouselImage: data.carouselImage?.toString(),
        meetingPlanId: data.meetingPlanId?.toString()
      })
      message.success(t('common.createSuccess'))
    } else {
      await SpecialMeetingApi.updateSpecialMeeting({
        ...data,
        carouselImage: data.carouselImage?.toString(),
        meetingPlanId: data.meetingPlanId?.toString()
      })
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
    router.back()
    delVisitedView(route)
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    meetingName: undefined,
    meetingSynopsis: undefined,
    startTime: undefined,
    endTime: undefined,
    isFreeMeeting: 0,
    meetingPlanId: [],
    meetingAddress: undefined,
    cover: undefined,
    carouselImage: [],
    details: undefined,
    sort: undefined,
    isTop: 0,
    createTime: undefined
  }
  formRef.value?.resetFields()
}

open(id === -1 ? 'create' : 'update', id === -1 ? undefined : id)
</script>
